package org.lex.swing.widgets.console.demo;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

import org.lex.swing.widgets.OutputStreamTextArea;
import org.lex.swing.widgets.console.demo.windows.CommandShell;

public class WindowsShellConsoleMainFrame extends JFrame {
	private JPanel pane = null;
	private JScrollPane scrollPane = null;
	private OutputStreamTextArea textArea = null;
	private JTextField commandTextField = null;
	private CommandShell cmd = null;

	public WindowsShellConsoleMainFrame() {
		super();
		initialize();
	}

	private CommandShell getCmd() {
		if (null == cmd)
			try {
				this.cmd = CommandShell.createShell(this.getTextArea().getWriter(), this.getTextArea().getWriter());
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		return cmd;
	}

	private void initialize() {
		this.setSize(450, 320);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setContentPane(getPane());
		this.setTitle("Console");
	}

	private JPanel getPane() {
		if (pane == null) {
			BorderLayout borderLayout = new BorderLayout();
			borderLayout.setVgap(1);
			pane = new JPanel();
			pane.setLayout(borderLayout);
			pane.add(getCommandTextField(), BorderLayout.NORTH);
			pane.add(getScrollPane(), BorderLayout.CENTER);
		}
		return pane;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTextArea());
		}
		return scrollPane;
	}

	private OutputStreamTextArea getTextArea() {
		if (textArea == null) {
			textArea = new OutputStreamTextArea();
			textArea.setLineWrap(false);
		}
		return textArea;
	}

	private JTextField getCommandTextField() {
		if (commandTextField == null) {
			commandTextField = new JTextField();
			commandTextField.addActionListener(new ActionListener() {
				public void actionPerformed(final ActionEvent e) {
					new SwingWorker<Void, Void>() {
						@Override
						protected Void doInBackground() throws Exception {
							String command = commandTextField.getText();
							commandTextField.setText("");
							getCmd().execute(command);
							return null;
						}
					}.execute();
				}
			});
		}
		return commandTextField;
	}
}
